package com.nf.health.app.chatservice.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.PathUtil;
import com.nf.health.app.AppModel;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.chatservice.bean.StatusBean;
import com.nf.health.app.http.Act;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.inquiry.docdetail.DocHomeOrderActivity;
import com.nf.health.app.models.HealthManagerStatus;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DealUiUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDiscountCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorAdvice;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorQuestion;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDrugAlert;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowHealthAlert;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowImageMessage;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowOnlyMessage;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowSystemBMCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowSystemCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowSystemHealthCard;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 单聊
 */
public class ChatActivity extends BaseActivity {


    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constants.DESCRIPTOR);

    private static final String TAG = ChatActivity.class.getSimpleName();
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;
    private static final int ITEM_PICTURE = 1;
    private static final int ITEM_TAKE_PICTURE = 2;
    private static final int ITEM_EVALUATION = 5;
    public static final String EXTRA_DOCTOR_TYPE = "extra_doctor_type";//暂时没发现用到，于是就注释掉了


    private int state_bm;//去报名状态值

    //消息类型
    private static final int MESSAGE_TYPE_RECV_HEALTH_ALERT = 1;
    private static final int MESSAGE_TYPE_RECV_DRUG_ALERT = 2;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_QUESTION = 3;
    private static final int MESSAGE_TYPE_RECV_IMAGE_MESSAGE = 4;
    private static final int MESSAGE_TYPE_RECV_ONLY_MESSAGE = 5;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_ADVICE = 6;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_CARD = 7;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_CARD = 8;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM = 9;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_BM = 10;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_HEALTH = 11;

    @Bind(R.id.btn_evaluate)
    Button btnEvaluate;
    @Bind(R.id.btn_buy_service)
    Button btnBuyService;
    @Bind(R.id.tv_chat_status)
    TextView tvChatStatus;
    @Bind(R.id.ll_service_end)
    LinearLayout llServiceEnd;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;
    @Bind(R.id.message_list)
    EaseChatMessageList messageList;
    @Bind(R.id.voice_recorder)
    EaseVoiceRecorderView voiceRecorderView;
    @Bind(R.id.input_menu)
    EaseChatInputMenu inputMenu;
    @Bind(R.id.tv_arrow_contact_bottom)
    TextView tv_arrow_contact_bottom;//显示健康联系人，绑定的家人的展开箭头
    @Bind(R.id.ll_arrow_right)
    LinearLayout ll_arrow_right;//显示健康联系人，绑定的家人的展开箭头
    @Bind(R.id.tv_content_contact)
    TextView tv_content_contact;//显示健康联系人，绑定的家人
    @Bind(R.id.ic_title_contactleft)
    TextView ic_title_contactleft;//显示健康联系人，绑定的家人
    @Bind(R.id.ll_contact_content)
    LinearLayout ll_contact_content;

    private AlertDialog alertDialog;

    public ChatActivity activityInstance;

    private String toChatUsername;
    protected int chatType;
    protected SwipeRefreshLayout swipeRefreshLayout;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected int[] itemStrings = {R.string.chat_picture, R.string.chat_camera, R.string.chat_evaluation};
    protected int[] itemdrawables = {R.drawable.ic_chat_picture,
            R.drawable.ic_chat_camera,
            R.drawable.ic_chat_evaluation};
    protected int[] itemIds = {ITEM_PICTURE, ITEM_TAKE_PICTURE, ITEM_EVALUATION};

    private static final String FLAG_STATE = "flagstate";////计划


    protected MyItemClickListener extendMenuItemClickListener;
    private ListView listView;
    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected EMConversation conversation;

    private boolean isMessageListInited;
    protected File cameraFile;
    private UserInfo userInfo;
    private StatusBean mStatusBean;
    private String status;


    String httpUrl;

    private int unreadMessageCount = 0 ;

    @Override
    protected void onCreate(Bundle arg0) {
        LogUtil.i(TAG, "oncreate");
        super.onCreate(arg0);
        userInfo = PreferenceHelper.getUser();
        activityInstance = this;
        // 直接设置为单聊
        chatType = EaseConstant.CHATTYPE_SINGLE;
        //聊天人或群id
        toChatUsername = getIntent().getExtras().getString(EaseConstant.EXTRA_USER_ID);

        provider.requestHomeState(FLAG_STATE);//获取健康团队解决状态

        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_chat);
        ButterKnife.bind(this);
        titlebarRightTv.setOnClickListener(this);
        initView();
        initListener();
    }

    private void initStatus() {
        provider.getServiceStatus(toChatUsername);
    }

    private void updateStatus() {
        if(mStatusBean !=  null){
            String serviceId = mStatusBean.getServicId();
            if(!TextUtils.isEmpty(serviceId)){
                provider.updateServiceStatus(toChatUsername,serviceId);
            }
        }
    }

    private void initView() {
        //设置标题
        if (chatType == EaseConstant.CHATTYPE_SINGLE) { // 单聊
            // 设置标题
            EaseUser easeUser = EaseUserUtils.getUserInfo(toChatUsername);
            if ( easeUser != null) {
                titlebarTitleTv.setText(easeUser.getNick());
            } else {
                titlebarTitleTv.setText(toChatUsername);
            }
        }

        titlebarRightView.setImageResource(R.drawable.comment_flower);
        listView = messageList.getListView();
        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu.init(null);
        inputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {
            @Override
            public void onSendMessage(String content) {
                // 发送文本消息
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        // 发送语音消息
                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
                    }
                });
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                //发送大表情(动态表情)
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
            }
        });

        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(com.hyphenate.easeui.R.color.holo_blue_bright, com.hyphenate.easeui.R.color.holo_green_light,
                com.hyphenate.easeui.R.color.holo_orange_light, com.hyphenate.easeui.R.color.holo_red_light);

        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //其他的一些view
        setUpView();
        //扩展栏view
        registerExtendMenuItem(2);
        ll_contact_content.setVisibility(View.GONE);//进来先隐藏签约人布局，防止无网是假数据的出现
    }

    private void setUpView() {
        onConversationInit();
        onMessageListInit();
        //下拉刷新
        setRefreshLayoutListener();
    }

    private void initListener() {
        btnBuyService.setOnClickListener(this);
        btnEvaluate.setOnClickListener(this);
        titlebarRightView.setOnClickListener(this);
    }


    protected void onConversationInit() {
        // 获取当前conversation对象
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);

        //标记未读消息数量，用于判断是显示分享健康币
        unreadMessageCount = conversation.getUnreadMsgCount() ;
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }



    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, new CustomChatRowProvider());
        //设置list item里的控件的点击事件
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            List<EMMessage> messages;
                            try {
                                messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
                                        pagesize);
                            } catch (Exception e1) {
                                swipeRefreshLayout.setRefreshing(false);
                                return;
                            }
                            if (messages.size() > 0) {
                                messageList.refreshSeekTo(messages.size() - 1);
                                if (messages.size() != pagesize) {
                                    haveMoreData = false;
                                }

                            } else {
                                haveMoreData = false;
                            }

                            isloading = false;

                        } else {
                            Toast.makeText(ChatActivity.this, getResources().getString(com.hyphenate.easeui.R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {//点击头像跳到医生主页

                //如果不是系统消息，再跳转
                if (!"-2".equals(status)) {
                    if (toChatUsername.equals(username)) {
                        Bundle bundle = new Bundle();
                        bundle.putString(DocDetailActivity.DOCTORID, username);
                        ActivityUtils.showActivity(ChatActivity.this, DocDetailActivity.class, bundle);
                    }
                }
            }

            @Override
            public void onResendClick(final EMMessage message) {
                new EaseAlertDialog(activityInstance, com.hyphenate.easeui.R.string.resend, com.hyphenate.easeui.R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        resendMessage(message);
                    }
                }, true).show();
            }

            @Override
            public void onBubbleLongClick(EMMessage message) {
                //TODO
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                //TODO
                return false;
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 设置扩展栏
     */
    private void registerExtendMenuItem(int count) {
        for (int i = 0; i < count; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
        //设置扩展栏列数为count,默认为4,解决三个item不能居中的问题
        inputMenu.getExtendMenu().setNumColumns(count);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }
    }

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message);
    }

    protected void sendBigExpressionMessage(String name, String identityCode) {
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        sendMessage(message);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        sendMessage(message);
    }


    protected void sendMessage(EMMessage message) {
//        if(chatFragmentListener != null){
//            //设置扩展属性
//            chatFragmentListener.onSetMessageAttributes(message);
//        }
        String name = userInfo.getRname();
        if(TextUtils.isEmpty(name)){
            name = userInfo.getNick();
        }
        if (userInfo != null && !TextUtils.isEmpty(name)) {
            message.setAttribute(Constants.EMContact.EF_USERNAME, name);
        } else {
            message.setAttribute(Constants.EMContact.EF_USERNAME, toChatUsername);
        }
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getHimg())) {
            message.setAttribute(Constants.EMContact.EF_USERICON, userInfo.getHimg());
        } else {
            message.setAttribute(Constants.EMContact.EF_USERICON, "");
        }
        //发送EF_DoctorType附加字段
//        if (doctorType != null) {
//            message.setAttribute("EF_DoctorType", doctorType);
//        } else {
//            //默认是普通患者发送
//            message.setAttribute("EF_DoctorType", "10_");
//        }
        //发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
        //刷新ui
        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
        //更新服务状态
        updateStatus();
    }


    public void resendMessage(EMMessage message) {
        message.setStatus(EMMessage.Status.CREATE);
        EMClient.getInstance().chatManager().sendMessage(message);
        messageList.refresh();
        //从新发送时更新状态
        updateStatus();
    }


    /**
     * 扩展菜单栏item点击事件
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE: // 拍照
                    selectPicFromCamera();
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal(); // 图库选择图片
                    break;
                case ITEM_EVALUATION: // 评价
                    inputMenu.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 照相获取图片
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isExitsSdcard()) {
            Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            }
        }
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = activityInstance.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendImageMessage(file.getAbsolutePath());
        }

    }

    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            for (EMMessage message : messages) {
                String username = null;
                // 群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }

                // 如果是当前会话的消息，刷新聊天页面
                if (username.equals(toChatUsername)) {
                    messageList.refreshSelectLast();
                    // 声音和震动提示有新消息
                    EaseUI.getInstance().getNotifier().viberateAndPlayTone(message);
                } else {
                    // 如果消息不是和当前聊天ID的消息
                    EaseUI.getInstance().getNotifier().onNewMsg(message);
                }
                //通知
                try {
                    EaseUser user = new EaseUser(message.getFrom());
                    String name = message.getStringAttribute(Constants.EMContact.EF_USERNAME);
                    String himg = message.getStringAttribute(Constants.EMContact.EF_USERICON);
                    user.setNick(name);
                    user.setAvatar(himg);
                    AppModel.getInstatnce().saveContact(user);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
        EaseUI.getInstance().pushActivity(activityInstance);
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        initStatus();
    }

    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);

        // 把此activity 从foreground activity 列表里移除
        EaseUI.getInstance().popActivity(activityInstance);
    }


    /**
     * 响应点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_buy_service:
                //买服务
                String serviceType = mStatusBean.getServicType();//1家庭服务，2付费咨询 -1无服务
                if ("1".equals(serviceType)) {
                    Bundle docDetailBundle2 = new Bundle();
                    docDetailBundle2.putString(Constants.DOCTOR_ID, toChatUsername);
                    ActivityUtils.showActivity(this, DocHomeOrderActivity.class, docDetailBundle2);
                } else {
                    Bundle docDetailBundle = new Bundle();
                    docDetailBundle.putString(DocDetailActivity.DOCTORID, toChatUsername);
                    ActivityUtils.showActivity(this, DocDetailActivity.class, docDetailBundle);
                }
                break;
            case R.id.btn_evaluate:
                //服务结束评价
                Bundle commentBundle = new Bundle();
                commentBundle.putString(Constants.DOCTOR_ID, toChatUsername);
                commentBundle.putString(EvaluateDoctorActivity.SERVICE_ID, mStatusBean.getServicId());
                commentBundle.putString(EvaluateDoctorActivity.IS_END, "2");//	1 可以再评价，2 评价结束不可评价
                ActivityUtils.showActivity(this, EvaluateDoctorActivity.class, commentBundle);
                break;
            case R.id.titlebar_right_view:
                //服务过程中评价
                Bundle comment = new Bundle();
                comment.putString(Constants.DOCTOR_ID, toChatUsername);
                comment.putString(EvaluateDoctorActivity.SERVICE_ID, mStatusBean.getServicId());
                if ("-3".equals(mStatusBean.getStatus()) ||"-4".equals(mStatusBean.getStatus())) {
                    comment.putString(EvaluateDoctorActivity.IS_END, "3");//	1 可以再评价，2 评价结束不可评价 3 健康助手,或者健康银行评价
                } else {
                    comment.putString(EvaluateDoctorActivity.IS_END, "1");//	1 可以再评价，2 评价结束不可评价
                }

                ActivityUtils.showActivity(this, EvaluateDoctorActivity.class, comment);
                break;
            default:
                break;
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        if (Act.Flag.UPDATE_SERVICE_STATUS.equals(actionName)) {
            //不做操作,主要是不显示progressbar
        } else {
            super.handleActionStart(actionName, object);
        }
    }

    /**
     * 网络请求处理
     *
     * @param actionName
     * @param object
     */
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.GET_SERVICE_STATUS_FLG.equals(actionName) || Act.Flag.UPDATE_SERVICE_STATUS.equals(actionName)) {
            mStatusBean = (StatusBean) object;
            updateViewByStatusBean(mStatusBean);
            DealUiUtils.setMyConactTextConMsg(mStatusBean,tv_content_contact,ll_arrow_right,tv_arrow_contact_bottom,ic_title_contactleft,ll_contact_content);
        } else if (FLAG_STATE.equals(actionName)) { /********获取点击状态***：健康管理团队 recycleView Hodler 的position为0*******/
            HealthManagerStatus state = (HealthManagerStatus) object;
           // 3未购买设备,1未报名,2已报名
            state_bm = state.getState();
        }
    }

    /**
     * 根据服务状态来更新界面
     * 逻辑状态有点多
     * <p/>
     * 服务状态status 1正常，2结束， -1无服务，-2系统消息，-3健康助手，-4健康银行
     *
     * @param mStatusBean
     */
    private void updateViewByStatusBean(StatusBean mStatusBean) {
        //设置标题
        if (chatType == EaseConstant.CHATTYPE_SINGLE) { // 单聊
            // 设置标题
            if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
                EaseUser user = EaseUserUtils.getUserInfo(toChatUsername);
                String name =  user.getNick();
                if (mStatusBean.getServicName().contains("无服务")) {
                    titlebarTitleTv.setText(name);
                } else {
                    titlebarTitleTv.setText(name + "(" + mStatusBean.getServicName() + ")");
                }
            } else {
                titlebarTitleTv.setText(toChatUsername);
            }
        }

        //服务状态
        status = mStatusBean.getStatus();
        String noteStatus = mStatusBean.getNoteStatus();//评价状态
        switch (status) {
            case "1"://服务中,正常
                llServiceEnd.setVisibility(View.GONE);
                inputMenu.setVisibility(View.VISIBLE);
                if ("0".equals(noteStatus)) {
                    //没有评价,显示右上角评价按钮
                    titlebarRightView.setVisibility(View.VISIBLE);
                } else {
                    titlebarRightView.setVisibility(View.INVISIBLE);
                }
                break;
            case "2": //服务结束
                llServiceEnd.setVisibility(View.VISIBLE);
                tvChatStatus.setText(mStatusBean.getEndstr());
                inputMenu.setVisibility(View.GONE);
                titlebarRightView.setVisibility(View.INVISIBLE);
                //服务结束,评价完成,只能跳转到购买服务
                if ("2".equals(noteStatus) || "-1".equals(noteStatus)) {
                    btnEvaluate.setVisibility(View.GONE);
                }
                break;

            case "-1"://无服务
                titlebarRightView.setVisibility(View.INVISIBLE);
                llServiceEnd.setVisibility(View.VISIBLE);
                tvChatStatus.setText(mStatusBean.getEndstr());
                inputMenu.setVisibility(View.GONE);
                btnEvaluate.setVisibility(View.GONE);
                break;
            case "-2"://  "-2"系统消息
                llServiceEnd.setVisibility(View.GONE);
                inputMenu.setVisibility(View.GONE);
                titlebarRightView.setVisibility(View.INVISIBLE);
                break;
            case "-3"://  "-3"健康助手,可以随时聊
                titlebarRightView.setVisibility(View.VISIBLE);
                llServiceEnd.setVisibility(View.GONE);
                inputMenu.setVisibility(View.VISIBLE);
                break;
            case "-4"://  "-4"健康银行
                titlebarRightView.setVisibility(View.VISIBLE);
                llServiceEnd.setVisibility(View.GONE);
                inputMenu.setVisibility(View.GONE);
                break;
            default:
                llServiceEnd.setVisibility(View.GONE);
                inputMenu.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onDestroy() {
        LogUtil.i(TAG, "ondestory");
        super.onDestroy();
    }

    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            return 11;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            try {
                if (message.getType() == EMMessage.Type.TXT) {
                    String msgType = message.getStringAttribute("EF_MessageType");
                    if (msgType.equals(Constants.MESSAGE_TYPE_RECV_HEALTH_ALERT)) {
                        return MESSAGE_TYPE_RECV_HEALTH_ALERT;

                    } if (msgType.equals(Constants.MESSAGE_TYPE_RECV_HEALTH_ALERT)) {
                        return MESSAGE_TYPE_RECV_HEALTH_ALERT;

                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DRUG_ALERT)) {
                        return MESSAGE_TYPE_RECV_DRUG_ALERT;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_QUESTION)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_QUESTION;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_IMAGE_MESSAGE)) {
                        return MESSAGE_TYPE_RECV_IMAGE_MESSAGE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_ONLY_MESSAGE)) {
                        return MESSAGE_TYPE_RECV_ONLY_MESSAGE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_ADVICE)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_ADVICE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_CARD)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_CARD;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_CARD)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_CARD;

                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM;
                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_BM)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_BM;
                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_HEALTH)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_HEALTH;
                    }
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            try {
                if (message.getType() == EMMessage.Type.TXT) {
                    String msgType = message.getStringAttribute("EF_MessageType");
                    if (msgType.equals(Constants.MESSAGE_TYPE_RECV_HEALTH_ALERT)) {//健康预警
                        return new EaseChatRowHealthAlert(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DRUG_ALERT)) {//用药提醒
                        return new EaseChatRowDrugAlert(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_QUESTION)) {//医生问卷
                        return new EaseChatRowDoctorQuestion(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_IMAGE_MESSAGE)) {//图文消息
                        return new EaseChatRowImageMessage(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_ONLY_MESSAGE)) {//纯文消息
                        return new EaseChatRowOnlyMessage(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_ADVICE)) {//医嘱计划
                        return new EaseChatRowDoctorAdvice(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_CARD)) {//医生名片
                        return new EaseChatRowDoctorCard(ChatActivity.this, message, position, adapter,state_bm);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_CARD)) {//医生优惠码
                        return new EaseChatRowDiscountCard(ChatActivity.this, message, position, adapter,state_bm);

                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM)) {//[抢红包资格]"
                        return new EaseChatRowSystemCard(ChatActivity.this, message, position, adapter,state_bm);

                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_BM)) {//健康课题报名资格
                        return new EaseChatRowSystemBMCard(ChatActivity.this, message, position, adapter,state_bm);



                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM_HEALTH)) {//健康币奖励
                        return new EaseChatRowSystemHealthCard(ChatActivity.this, message, position, adapter,state_bm);
                    }
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

}
